package com.safeluck.videofunc;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;

import com.alivc.live.pusher.AlivcAudioAACProfileEnum;
import com.alivc.live.pusher.AlivcFpsEnum;
import com.alivc.live.pusher.AlivcLivePushCameraTypeEnum;
import com.alivc.live.pusher.AlivcLivePushConfig;
import com.alivc.live.pusher.AlivcLivePushError;
import com.alivc.live.pusher.AlivcLivePushErrorListener;
import com.alivc.live.pusher.AlivcLivePushInfoListener;
import com.alivc.live.pusher.AlivcLivePushNetworkListener;
import com.alivc.live.pusher.AlivcLivePusher;
import com.alivc.live.pusher.AlivcPreviewOrientationEnum;
import com.alivc.live.pusher.AlivcAudioAACProfileEnum;
import com.alivc.live.pusher.AlivcQualityModeEnum;
import com.alivc.live.pusher.AlivcResolutionEnum;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements Camera.PreviewCallback, SurfaceHolder.Callback {

    private static final String TAG = "VideoFunc";
    String[] permissons = new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE
    ,Manifest.permission.RECORD_AUDIO,Manifest.permission.INTERNET};
    private static final  int REQUESTCODE = 100;
    private SurfaceHolder surfaceHolder;
    SurfaceView surfaceView;
    private TextView textView;


//    private Camera camera;

//    private String mPushUrl= "rtmp://video-center-bj.alivecdn.com/AppName/StreamName?vhost=live.aaej.cn";
    private String mPushUrl="rtmp://push-demo-rtmp.aliyunlive.com/test/stream";
    private AlivcLivePusher alivcLivePusher;

private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView =  (SurfaceView) findViewById(R.id.surfaceView);
        textView = findViewById(R.id.tv_addr);
        initCamera();
        initPusher();
    }

    private void initPusher() {
        AlivcLivePushConfig mAlivcLivePushConfig = new AlivcLivePushConfig();//初始化推流配置类
        mAlivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_540P);//分辨率540P，最大支持720P
        mAlivcLivePushConfig.setFps(AlivcFpsEnum.FPS_20); //建议用户使用20fps
        mAlivcLivePushConfig.setEnableBitrateControl(true); // 打开码率自适应，默认为true
        mAlivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_PORTRAIT); // 默认为竖屏，可设置home键向左或向右横屏。
        mAlivcLivePushConfig.setAudioProfile(AlivcAudioAACProfileEnum.AAC_LC);//设置音频编码模式
        mAlivcLivePushConfig.setCameraType(AlivcLivePushCameraTypeEnum.CAMERA_TYPE_BACK);
        mAlivcLivePushConfig.setEnableBitrateControl(true);// 打开码率自适应，默认为true
        mAlivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_LANDSCAPE_HOME_LEFT);

        //QM_RESOLUTION_FIRST 清晰度优先模式。SDK内部会对码率参数进行配置，优先保障推流视频的清晰度。
        mAlivcLivePushConfig.setQualityMode(AlivcQualityModeEnum.QM_RESOLUTION_FIRST);



//        初始化
//
//        在配置好推流参数后，可以使用推流SDK的init方法进行初始化
        alivcLivePusher = new AlivcLivePusher();
        alivcLivePusher.init(getApplicationContext(),mAlivcLivePushConfig);
        //AlivcLivePusher目前不支持多实例，所以一个init必须对应有一个destory。  alivcLivePusher.destroy();

        alivcLivePusher.setLivePushInfoListener(new AlivcLivePushInfoListener() {
            @Override
            public void onPreviewStarted(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPreviewStarted: ");
                int streamId = (int) (Math.random()*9999);
                mPushUrl = mPushUrl+streamId;
                Log.i(TAG, "onPreviewStarted: url= "+mPushUrl);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(mPushUrl);
                    }
                });
                alivcLivePusher.startPushAysnc(mPushUrl);

            }

            @Override
            public void onPreviewStoped(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPreviewStoped: ");
            }

            @Override
            public void onPushStarted(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPushStarted: ");

            }

            @Override
            public void onPushPauesed(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPushPauesed: ");
            }

            @Override
            public void onPushResumed(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPushResumed: ");
            }

            @Override
            public void onPushStoped(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPushStoped: ");
            }

            @Override
            public void onPushRestarted(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPushRestarted: ");
            }

            @Override
            public void onFirstFramePreviewed(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onFirstFramePreviewed: ");
            }

            @Override
            public void onDropFrame(AlivcLivePusher alivcLivePusher, int i, int i1) {

            }

            @Override
            public void onAdjustBitRate(AlivcLivePusher alivcLivePusher, int i, int i1) {

            }

            @Override
            public void onAdjustFps(AlivcLivePusher alivcLivePusher, int i, int i1) {

            }
        });


        alivcLivePusher.setLivePushErrorListener(new AlivcLivePushErrorListener() {
            @Override
            public void onSystemError(AlivcLivePusher alivcLivePusher, AlivcLivePushError alivcLivePushError) {
                Log.i(TAG, "onSystemError: "+alivcLivePushError.toString());
                //当出现onSystemError系统级错误时，您需要退出直播。
                alivcLivePusher.stopPush();

            }

            @Override
            public void onSDKError(AlivcLivePusher alivcLivePusher, AlivcLivePushError alivcLivePushError) {
                Log.i(TAG, "onSDKError: "+alivcLivePushError.toString());
//                当出现onSDKError错误（SDK错误）时，有两种处理方式，选择其一即可：销毁当前直播，重新创建或调用restartPush/restartPushAsync重启AlivcLivePusher。
                alivcLivePusher.restartPushAync();
            }
        });

        alivcLivePusher.setLivePushNetworkListener(new AlivcLivePushNetworkListener() {
            @Override
            public void onNetworkPoor(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onNetworkPoor: ");
            }

            @Override
            public void onNetworkRecovery(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onNetworkRecovery: ");
            }

            @Override
            public void onReconnectStart(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onReconnectStart: ");
            }

            @Override
            public void onReconnectFail(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onReconnectFail: ");
            }

            @Override
            public void onReconnectSucceed(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onReconnectSucceed: ");
            }

            @Override
            public void onSendDataTimeout(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onSendDataTimeout: ");
            }

            @Override
            public void onConnectFail(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onConnectFail: ");
            }

            @Override
            public String onPushURLAuthenticationOverdue(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onPushURLAuthenticationOverdue: ");
                return null;
            }

            @Override
            public void onSendMessage(AlivcLivePusher alivcLivePusher) {
                Log.i(TAG, "onSendMessage: ");
            }
        });


//        开始预览
//
//        livePusher对象初始化完成之后，可以进行开始预览操作。预览时需要传入摄像头预览的显示SurfaceView。
    }

    private void initCamera() {
        for (String s: permissons){
            int checkResult = 0;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                checkResult = checkSelfPermission(s);
            }
            if (checkResult == PackageManager.PERMISSION_GRANTED){
                Log.i(TAG, "initCamera: 有该权限："+s);
            }else{
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(permissons,REQUESTCODE);
                }
            }
        }


//        int CameraNum = Camera.getNumberOfCameras();
//        if (CameraNum<=0){
//            throw new RuntimeException("没有相机");
//        }
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

//        camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
//
//
//        camera.setPreviewCallback(this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTCODE){
            for (int a:grantResults){
                Log.i(TAG, "onRequestPermissionsResult: permission:"+permissions[a]+"_result:"+grantResults[a]);
                if (a == PackageManager.PERMISSION_GRANTED){

                }else if (a ==PackageManager.PERMISSION_DENIED){
                    Log.i(TAG, "onRequestPermissionsResult: 拒绝");
                }
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onResume() {
        super.onResume();
//        退后台和锁屏
//
//        当app退后台或锁屏时，您可调用 AlivcLivePusher 的 pause()/resume()接口暂停/恢复推流。
//
//        对于非系统的音视频通话，sdk会采集声音并推送出去，您可以根据业务需求在退后台或锁屏时调用静音接口mAlivcLivePusher.setMute(true/false)来决定后台时是否采集音频;


    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.i(TAG, "surfaceCreated: ");

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.i(TAG, "surfaceChanged: ");
        if (alivcLivePusher != null){
            alivcLivePusher.startPreviewAysnc(surfaceView);
        }

//        if (camera != null){
//            rotateCamera(camera);
//            try {
//                camera.setPreviewDisplay(surfaceHolder);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            camera.stopPreview();
//            camera.startPreview();
//        }
    }

    /**
     * 旋转一下摄像头
     * @param camera
     */
    private void rotateCamera(Camera camera) {
//        camera.setDisplayOrientation(90);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(TAG, "surfaceDestroyed: ");
//        if (camera != null){
//            camera.stopPreview();
//            try {
//                camera.setPreviewDisplay(null);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (camera != null){
//
//            camera.release();
//        }
        if (alivcLivePusher != null){
            alivcLivePusher.destroy();
        }
    }
}
